﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.houseWork.Helper;

namespace CIT.WMS.input
{
    public partial class CGInput : Form
    {
        bool flag = false;
        bool result = false;
        string PO_TypeCode = string.Empty;//1：采购订单；2：委外订单；3：客供来料订单

        public CGInput()
        {
            InitializeComponent();
            databind();
        }

        private void databind()
        {


            string strSql = string.Format(@"SELECT PO,POID FROM dbo.T_Bllb_POMain_tbpm WHERE Status='0' ORDER BY CreateTime DESC");
            DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            DataRow dr = dt_po.NewRow();
            dr["PO"] = string.Empty;
            dr["POID"] = string.Empty;
            dt_po.Rows.InsertAt(dr, 0);
            cbo_PO.DisplayMember = "PO";
            cbo_PO.ValueMember = "POID";
            cbo_PO.DataSource = dt_po;

            strSql = string.Format(@"SELECT Storage_SN,Storage_Name FROM T_Bllb_Storage_tbs");
            DataTable dt_s = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            cbo_Storage.DisplayMember = "Storage_Name";
            cbo_Storage.ValueMember = "Storage_SN";
            cbo_Storage.DataSource = dt_s;
         
        }

        private void txt_reelid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                ClearControl();
                string POID = string.Empty;
               

                //供应商代码|料号|唯一码|数量|生产日期（datacode或批次）|订单号|行号
                string[] strs = txt_reelid.Text.Trim().Split('|');
                if (strs.Length != 7)
                {
                    DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, "select Status,POID,PO_TypeCode from T_Bllb_POMain_tbpm where PO='" + txt_reelid.Text.Trim() + "'", new CIT.WMS.MESWcf.CmdParameter[0]);
                    if ( dt_po.Rows.Count== 0)//若是输入的不是采购单，那么就认为是来料条码
                    {
                        lbl_msg.Text = "物料条码有误或采购单不存在.";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    else //判断采购单是否正确
                    {
                        if (SqlInput.ChangeNullToString(dt_po.Rows[0][0]) == "2")
                        {
                            lbl_msg.Text = "来料所属采购单已关闭.";
                            lbl_msg.ForeColor = Color.Red;
                        
                        }
                        else
                        {
                            cbo_PO.Text = txt_reelid.Text.Trim();
                            lbl_msg.Text = "采购单设置成功.";
                            lbl_msg.ForeColor = Color.Green;
                        }
                        PO_TypeCode = dt_po.Rows[0]["PO_TypeCode"].ToString();//订单类型
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                 
                }
                else
                {
                    if (cbo_PO.Text== string.Empty)
                    {
                        lbl_msg.Text = "请选择采购单";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                
                    //string[] strs = txt_reelid.Text.Trim().Split('|');
                    if (strs.Length == 7)
                    {
                        string po = strs[5].ToString();//采购订单号
                        if (po != cbo_PO.Text.Trim())
                        {
                            lbl_msg.Text = "物料不属于当前采购单";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        string strSql = string.Empty;
                        strSql = string.Format(@"SELECT * FROM dbo.T_Bllb_StockInfo_tbsi WHERE SerialNumber = '{0}'",txt_reelid.Text.Trim());
                        DataTable dt_sn = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_sn.Rows.Count > 0)
                        {
                            lbl_msg.Text = "物料已入库";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        string lot_no = strs[2].ToString();//批次号（唯一码）
                        string poid = string.Empty;//采购订单ID
                        string doc_no = string.Empty;//清点单号
                        string rownumber = string.Empty;//行号
                        string MaterialCode = strs[1].ToString(); //料号
                        string DateCode = strs[4].ToString(); //datacode
                        string PO_DetailID=string.Empty;
                        int qty=0;
                        qty = SqlInput.ChangeNullToInt(strs[3].ToString(), 0);//数量
                   
                        rownumber = strs[6].ToString();//行号
                        strSql = string.Format(@"SELECT B.PO_DetailID,B.Quantity,B.ClearQty,B.POID FROM  dbo.T_Bllb_PODetail_tbpd B  WHERE B.PO='{0}' AND B.RowNumber='{1}' and B.MaterialCode='{2}'", po, rownumber, MaterialCode);

                        DataTable dt_podetail = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if(dt_podetail.Rows.Count==0)
                        {
                             lbl_msg.Text = "采购单中不存在此物料.";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        poid = SqlInput.ChangeNullToString(dt_podetail.Rows[0]["POID"]);//采购单ID
                        PO_DetailID = dt_podetail.Rows[0][0].ToString();//采购单字表ID
                        if (PO_TypeCode=="1")//采购订单要校验品质
                        {
                            DataTable dt_check = Utils.NMS.QueryDataTable(Utils.uContext, string.Format(@"SELECT B.PO,A.ChooseFlag,B.CHECK_RESULT
 FROM dbo.T_Bllb_IQCProduct_tbip A LEFT JOIN dbo.T_Bllb_IQCDoc_tbid B ON A.IQC_NO=B.IQC_NO
WHERE A.SERIAL_NUMBER='{0}'", txt_reelid.Text.Trim()), new CIT.WMS.MESWcf.CmdParameter[0]);
                            if (dt_check.Rows.Count == 0)
                            {
                                ClearControl();
                                lbl_msg.Text = "物料SN未清点.";
                                lbl_msg.ForeColor = Color.Red;
                                txt_reelid.Text = string.Empty; ;
                                txt_reelid.Focus();
                                return;
                            }
                            else
                            {
                                string check_result = SqlInput.ChangeNullToString(dt_check.Rows[0]["CHECK_RESULT"]);//审核结果
                                string msg = string.Empty;
                                bool isOk = true;
                                if (check_result == string.Empty || check_result == "0")
                                {
                                    msg = "物料SN所在的IQC检验未审核，不能入库";
                                    isOk = false;
                                }
                                else if (check_result == "2")
                                {

                                    msg = "物料SN是被判定为拒收物料、不能入库";
                                    isOk = false;
                                }
                                else if (check_result == "5" & SqlInput.ChangeNullToString(dt_check.Rows[0]["ChooseFlag"]) != "Y")
                                {
                                    msg = "物料SN所在IQC检验单审核结果挑料，但该物料不在挑料范围、不能入库";
                                    isOk = false;
                                }
                                if (!isOk)
                                {
                                    ClearControl();
                                    lbl_msg.Text = msg;
                                    lbl_msg.ForeColor = Color.Red;
                                    txt_reelid.Text = string.Empty; ;
                                    txt_reelid.Focus();
                                    return;
                                }

                            }
                        }

//                        strSql = string.Format(@"SELECT SerialNumber FROM T_Bllb_StorageDocDetail_tbsdd A LEFT JOIN 
//dbo.T_Bllb_StorageDoc_tbsd B ON A.S_Doc_NO=B.S_Doc_NO WHERE  A.SerialNumber='{0}' AND B.S_Doc_Type in ('3','4','12')", txt_reelid.Text.Trim());
//                        DataTable dt_serial= Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
//                        if (dt_serial.Rows.Count > 0)
//                        {
                       
//                            lbl_msg.Text = "此物料已入库";
//                            lbl_msg.ForeColor = Color.Red;
//                            txt_reelid.Text = string.Empty; ;
//                            txt_reelid.Focus();
//                            return;
//                        }
                        //判断清点单是否已生成，若无则自动生成入库单
                        string doc_type = "";
                        switch (PO_TypeCode)
                        {
                            case "1":                              
                                doc_type = "3";
                                break;
                            case "2":                              
                                doc_type = "13";
                                break;
                            case "3":                        
                                doc_type = "12";
                                break;
                            default:
                                return;
                        }


                        DataTable dt_doc = Utils.NMS.QueryDataTable(Utils.uContext, string.Format("SELECT  S_Doc_NO  FROM T_Bllb_StorageDoc_tbsd WHERE PO='{0}'and Create_Time>=CONVERT(CHAR(10),GETDATE(),120) AND S_Doc_Type in ('{2}') and Target_Storage='{1}' order by S_Doc_NO desc", cbo_PO.Text.Trim(), cbo_Storage.SelectedValue.ToString(), doc_type), new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_doc.Rows.Count == 0)
                        {
                            dt_doc = Utils.NMS.QueryDataTable(Utils.uContext, string.Format("SELECT  RIGHT(S_Doc_NO,4)+1  FROM T_Bllb_StorageDoc_tbsd WHERE Create_Time>=CONVERT(CHAR(10),GETDATE(),120) AND S_Doc_Type in ('{0}') order by S_Doc_NO desc", doc_type), new CIT.WMS.MESWcf.CmdParameter[0]);
                            if (dt_doc.Rows.Count > 0)
                            {
                                switch (PO_TypeCode)
                                { 
                                    case "1":
                                        doc_no = "CGR" + DateTime.Now.ToString("yyMMdd") + SqlInput.ChangeNullToInt(dt_doc.Rows[0][0], 0).ToString("0000");
                                        doc_type = "3";
                                        break;
                                    case "2":
                                        doc_no = "WWR" + DateTime.Now.ToString("yyMMdd") + SqlInput.ChangeNullToInt(dt_doc.Rows[0][0], 0).ToString("0000");
                                        doc_type = "13";
                                        break;
                                    case "3":
                                        doc_no = "KGR" + DateTime.Now.ToString("yyMMdd") + SqlInput.ChangeNullToInt(dt_doc.Rows[0][0], 0).ToString("0000");
                                        doc_type = "12";
                                        break;
                                    default:
                                        return;
                                }
                                
                            }
                            else
                            {
                                switch (PO_TypeCode)
                                {
                                    case "1":
                                        doc_no = "CGR" + DateTime.Now.ToString("yyMMdd") + "0001";
                                        doc_type = "3";
                                        break;
                                    case "2":
                                        doc_no = "WWR" + DateTime.Now.ToString("yyMMdd") + "0001";
                                        doc_type = "13";
                                        break;
                                    case "3":
                                        doc_no = "KGR" + DateTime.Now.ToString("yyMMdd") + "0001";
                                        doc_type = "12";
                                        break;
                                    default:
                                        return;
                                }
                            }
                            if (doc_type == string.Empty)
                            {
                                lbl_msg.Text = "采购类型错误，请检查数据";
                                lbl_msg.ForeColor = Color.Red;
                                txt_reelid.Text = string.Empty; ;
                                txt_reelid.Focus();
                                return;
                            }
                            strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDoc_tbsd
                                                    ( S_Doc_NO ,
                                                      S_Doc_Type ,
                                                      Create_Time ,
                                                      Creator ,
                                                      PO ,
                                                      POID,Target_Storage
                                                    )
                                            VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                      '{4}' , -- S_Doc_Type - nvarchar(10)
                                                      GETDATE() , -- Create_Time - datetime
                                                      '{1}' , -- Creator - nvarchar(50)
                                                      '{2}' , -- PO - nvarchar(50)
                                                      '{3}', -- POID - nvarchar(50)      
                                                      '{5}'
                                                    )", doc_no, Utils.uContext.UserIDk__BackingField , po, poid,doc_type,cbo_Storage.SelectedValue.ToString());  //供应商代码|料号|唯一码|数量|生产日期（datacode或批次）|订单号|行号
            
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                       
                        }
                        else
                        {
                            doc_no = dt_doc.Rows[0][0].ToString();
                        }
                        int totalQty = 0;
                        strSql = string.Format(@"SELECT S_Doc_NO,QTY FROM T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND RowNumber='{1}'", doc_no, rownumber);
                        //判断采购入库单中是否已存在某物料
                        DataTable dt_doc_material = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    
                        if (dt_doc_material.Rows.Count == 0)
                        {  
                            strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDocMaterial_tsdm
                                                    ( S_Doc_NO ,
                                                      MaterialCode ,
                                                      QTY ,
                                                      RowNumber ,
                                                      PO_DetailID 
                                                    )
                                            VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                      '{1}' , -- MaterialCode - nvarchar(50)
                                                      {2} , -- QTY - int
                                                      {3} , -- RowNumber - int
                                                      '{4}'  -- PO_DetailID - nvarchar(50) 
                                                    )", doc_no, MaterialCode, qty, rownumber, PO_DetailID);
                  
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                            totalQty = qty;
                        }
                        else
                        {
                          
                            strSql = string.Format(@"UPDATE T_Bllb_StorageDocMaterial_tsdm SET QTY=QTY+{2} WHERE S_Doc_NO='{0}' AND RowNumber={1}",doc_no,rownumber,qty);
                      
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                            totalQty = SqlInput.ChangeNullToInt(dt_doc_material.Rows[0]["QTY"].ToString(), 0) + qty;
                        }

                        strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDocDetail_tbsdd
                                                ( S_Doc_NO ,
                                                  MaterialCode ,
                                                  QTY ,
                                                  Create_Time ,
                                                  Creator ,
                                                  SerialNumber ,  
                                                  RowNumber ,
                                                  PO_DetailID,Lot_No
                                                )
                                        VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                  '{1}' , -- MaterialCode - nvarchar(50)
                                                  {2} , -- QTY - int
                                                  GETDATE() , -- Create_Time - datetime
                                                  '{3}' , -- Creator - nvarchar(50)
                                                  '{4}' , -- SerialNumber - nvarchar(50)   
                                                  {5} , -- RowNumber - int
                                                  '{6}',  -- PO_DetailID - nvarchar(50)
                                                   '{7}'
                                                )", doc_no, MaterialCode, qty, Utils.uContext.UserIDk__BackingField, txt_reelid.Text.Trim(), rownumber, PO_DetailID, lot_no);
                         Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                         lbl_TotalQty.Text = totalQty.ToString();
                         lbl_QTY.Text = qty.ToString();
                         lbl_PO.Text = po.ToString();
                         lbl_MaterialCode.Text = MaterialCode;
                         lbl_RowNumber.Text = rownumber;
                        //库存信息保存
                         strSql = string.Format(@"insert into dbo.T_Bllb_StockInfo_tbsi
        (
          Storage_SN ,
          QTY ,
          In_Time ,
          SerialNumber ,
          MaterialCode,
          DateCode
        )
values  ( 
          '{0}' , -- Storage_SN - nvarchar(50)
          '{1}' , -- QTY - int
          getDate() , -- In_Time - datetime
          '{2}' , -- SerialNumber - nvarchar(200)   
           '{3}',
           '{4}'
        )", cbo_Storage.SelectedValue.ToString(), qty, txt_reelid.Text.Trim(), MaterialCode, DateCode);
                         Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                   

                        //采购入库数累计
                         strSql = string.Format(@" UPDATE T_Bllb_PODetail_tbpd SET CurrentReceiveQty= ISNULL(CurrentReceiveQty,0)+{3}  WHERE POID='{0}' AND RowNumber='{1}' and MaterialCode='{2}'", poid, rownumber, MaterialCode, qty);
                        Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                    }
                    else
                    {
                        lbl_msg.Text = "物料条码不符合，无法解析";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    lbl_msg.Text = "OK";
                    lbl_msg.ForeColor = Color.Green;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                }
             
            }
        }

        private void cbo_PO_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearControl();
        }

        private void ClearControl()
        {
            lbl_MaterialCode.Text = string.Empty;//料号
            lbl_PO.Text = string.Empty;//采购单
            lbl_QTY.Text = string.Empty;//当前物料数量
            lbl_TotalQty.Text = string.Empty;//入库总数
            lbl_msg.Text = string.Empty;//提示信息
            lbl_RowNumber.Text = string.Empty;//行号
        }

        private void cbo_PO_LostFocus(object sender, EventArgs e)
        {
            if (cbo_PO.Text.Trim() != string.Empty)
            {
                string strSql = string.Format(@"SELECT Status,PO_TypeCode FROM T_Bllb_POMain_tbpm WHERE PO = '{0}'", cbo_PO.Text.Trim());
                DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_po.Rows.Count == 0)
                {
                    lbl_msg.Text = "采购单不存在";
                    lbl_msg.ForeColor = Color.Red;
                    return;
                }
                else if (SqlInput.ChangeNullToString(dt_po.Rows[0][0]) == "2")
                {
                    lbl_msg.Text = "采购单已关闭";
                    lbl_msg.ForeColor = Color.Red;
                    return;
                }
                PO_TypeCode = dt_po.Rows[0]["PO_TypeCode"].ToString();
                lbl_msg.Text = "采购单设置OK";
                lbl_msg.ForeColor = Color.Green;
                return;
            
            }
        }
    }
}